<template>
  <div
    class="min-h-screen flex flex-col bg-gradient-to-br from-blue-100 to-purple-100 dark:from-gray-900 dark:to-gray-800 relative overflow-hidden">
    <!-- 背景气泡 -->
    <div class="absolute inset-0 pointer-events-none z-0">
      <div v-for="n in 12" :key="n" class="absolute rounded-full opacity-30 blur-2xl" :style="bubbleStyle(n)"></div>
    </div>
    <!-- 标题 -->
    <div class="w-full flex flex-col items-center pt-10 z-10 relative">
      <h2 class="text-3xl font-bold text-purple-700 dark:text-purple-300 mb-2 drop-shadow" ref="titleRef">留言树洞</h2>
      <p class="text-gray-500 dark:text-gray-300 text-center mb-4" ref="descRef">
        这里是大家的树洞，畅所欲言吧～
      </p>
    </div>
    <!-- 弹幕留言区 -->
    <div class="flex-1 w-full relative z-10 overflow-hidden select-none">
      <div v-for="(msg, idx) in danmuList" :key="msg.id" class="absolute whitespace-nowrap pointer-events-auto"
        :ref="el => setDanmuRef(el as HTMLElement, idx)" :style="{
          top: `${msg.top}px`,
          left: `${msg.left}px`,
          zIndex: 10,
          transition: 'none'
        }" @mouseenter="pauseDanmu(idx)" @mouseleave="resumeDanmu(idx)">
        <div
          class="inline-flex items-center bg-white/80 dark:bg-gray-900/80 border border-purple-100 dark:border-gray-700 rounded-2xl px-6 py-3 shadow-lg backdrop-blur-md transition hover:scale-105 hover:shadow-2xl cursor-pointer">
          <span class="font-bold text-purple-700 dark:text-purple-300 mr-2">{{ msg.name }}</span>
          <span class="text-xs text-gray-400 mr-3">{{ msg.time }}</span>
          <span class="text-gray-700 dark:text-gray-200 break-words">{{ msg.content }}</span>
        </div>
      </div>
      <div v-if="messages.length === 0" class="text-gray-400 text-center mt-12">暂无留言，快来抢沙发吧！</div>
    </div>


    <!-- 固定底部留言表单 -->
    <form @submit.prevent="submitMessage"
      class="fixed bottom-0 left-0 w-full bg-transparent dark:bg-transparent border-t border-gray-200 dark:border-gray-700 shadow-lg z-20 flex flex-col md:flex-row items-center gap-2 px-4 py-3"
      ref="formRef">
      <input v-model="name" type="text" placeholder="你的昵称"
        class="flex-1 md:w-40 px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 focus:ring-2 focus:ring-purple-300 dark:focus:ring-purple-700 outline-none bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-200 transition"
        required />
      <textarea v-model="content" rows="1" placeholder="写下你的留言..."
        class="flex-1 px-4 py-2 rounded-lg border border-gray-200 dark:border-gray-700 focus:ring-2 focus:ring-purple-300 dark:focus:ring-purple-700 outline-none bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-200 transition resize-none"
        required></textarea>
      <button type="submit"
        class="px-6 py-2 rounded-lg bg-purple-500 hover:bg-purple-600 text-white font-semibold shadow transition">
        留言
      </button>
    </form>


  </div>

</template>

<script setup lang="ts">
import { ref, nextTick, onMounted, watch } from 'vue'
import gsap from 'gsap'

const name = ref('')
const content = ref('')
const messages = ref<{ id: number, name: string, content: string, time: string }[]>([])

// 弹幕数据（包含动画状态）
const danmuList = ref<{ id: number, name: string, content: string, time: string, top: number, left: number, width: number, anim?: gsap.core.Tween }[]>([])

const titleRef = ref()
const descRef = ref()
const formRef = ref()
const danmuRefs = ref<HTMLElement[]>([])

const DANMU_HEIGHT = 56 // px
const DANMU_TOP_PADDING = 40 // px

// 随机气泡样式
function bubbleStyle(n: number) {
  const colors = [
    'bg-purple-200', 'bg-blue-200', 'bg-purple-300', 'bg-blue-300', 'bg-purple-100', 'bg-blue-100'
  ]
  const size = 60 + Math.random() * 80
  const left = Math.random() * 100
  const top = Math.random() * 100
  const color = colors[n % colors.length]
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${left}%`,
    top: `${top}%`,
    background: 'inherit',
    zIndex: 1,
    backgroundColor: `var(--tw-${color})`,
    animation: `float${n} 12s ease-in-out infinite alternate`
  }
}

// 生成一个随机的top高度，避免重叠
function getRandomTop() {
  const trackCount = Math.max(2, Math.floor((window.innerHeight - 200) / DANMU_HEIGHT))
  return DANMU_TOP_PADDING + Math.floor(Math.random() * trackCount) * DANMU_HEIGHT
}

// 弹幕动画
function launchDanmu(idx: number) {
  nextTick(() => {
    const el = danmuRefs.value[idx]
    if (!el) return
    const width = el.offsetWidth
    const screenW = window.innerWidth
    danmuList.value[idx].width = width
    danmuList.value[idx].left = screenW
    // 清理旧动画
    if (danmuList.value[idx].anim) danmuList.value[idx].anim!.kill()
    // 动画
    const duration = 8 + Math.random() * 4 // 8~12秒
    danmuList.value[idx].anim = gsap.fromTo(
      danmuList.value[idx],
      { left: screenW },
      {
        left: -width,
        duration,
        ease: 'linear',
        onUpdate: () => {
          if (el) el.style.left = `${danmuList.value[idx].left}px`
        },
        onComplete: () => {
          // 重新随机高度和从右侧进入
          danmuList.value[idx].top = getRandomTop()
          danmuList.value[idx].left = screenW
          danmuList.value[idx].anim = gsap.fromTo(
            danmuList.value[idx],
            { left: screenW },
            {
              left: -width,
              duration,
              ease: 'linear',
              onUpdate: () => {
                if (el) el.style.left = `${danmuList.value[idx].left}px`
              },
              onComplete: () => {
                // 递归循环
                launchDanmu(idx)
              }
            }
          )
        }
      }
    )
  })
}

// 悬浮暂停/恢复
function pauseDanmu(idx: number) {
  if (danmuList.value[idx].anim) danmuList.value[idx].anim!.pause()
}
function resumeDanmu(idx: number) {
  if (danmuList.value[idx].anim) danmuList.value[idx].anim!.resume()
}

// 设置ref
function setDanmuRef(el: HTMLElement | null, idx: number) {
  if (el) danmuRefs.value[idx] = el
}

// 新增留言
function submitMessage() {
  if (!name.value.trim() || !content.value.trim()) return
  const msg = {
    id: Date.now(),
    name: name.value,
    content: content.value,
    time: new Date().toLocaleString(),
    top: getRandomTop(),
    left: window.innerWidth,
    width: 0
  }
  messages.value.unshift(msg)
  // 弹幕也加一条
  danmuList.value.unshift({ ...msg })
  name.value = ''
  content.value = ''
  nextTick(() => {
    launchDanmu(0)
  })
}

// 初始动画
onMounted(() => {
  gsap.from(titleRef.value, { y: -40, opacity: 0, duration: 0.8, ease: 'power2.out' })
  gsap.from(descRef.value, { y: 20, opacity: 0, duration: 0.8, delay: 0.2, ease: 'power2.out' })
  gsap.from(formRef.value, { y: 40, opacity: 0, duration: 0.8, delay: 0.4, ease: 'power2.out' })
})

// 页面加载时自动为所有弹幕启动动画
watch(danmuList, (val) => {
  nextTick(() => {
    val.forEach((_, idx) => launchDanmu(idx))
  })
})

// 组件卸载时清理动画
import { onBeforeUnmount } from 'vue'
onBeforeUnmount(() => {
  danmuList.value.forEach(d => d.anim && d.anim.kill())
})
</script>

<style scoped>
/* 漂浮气泡动画 */
@keyframes float1 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-40px);
  }
}

@keyframes float2 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-60px);
  }
}

@keyframes float3 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-30px);
  }
}

@keyframes float4 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-50px);
  }
}

@keyframes float5 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-35px);
  }
}

@keyframes float6 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-55px);
  }
}

@keyframes float7 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-45px);
  }
}

@keyframes float8 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-38px);
  }
}

@keyframes float9 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-42px);
  }
}

@keyframes float10 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-48px);
  }
}

@keyframes float11 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-36px);
  }
}

@keyframes float12 {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-52px);
  }
}
</style>